package com.boot.config;

import com.boot.pojo.CustomUserDetail;
import com.boot.utils.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {
        // 1. 获取用户信息
        CustomUserDetail userDetail = (CustomUserDetail) authentication.getPrincipal();
        Long userId = userDetail.getId();

        // 2. 生成JWT令牌
        String token = jwtUtil.createToken(userId);

        // 3. 准备自定义响应体
        Map<String, Object> responseBody = new LinkedHashMap<>();
        responseBody.put("code", 200);
        responseBody.put("msg", "登录成功");
        responseBody.put("data", Map.of(
                "token", token,
                "userId", userId,
                "username", userDetail.getUsername()
                // 可以添加更多用户信息
        ));

        // 4. 设置响应
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());

        // 5. 写入响应流
        try (PrintWriter writer = response.getWriter()) {
            new ObjectMapper().writeValue(writer, responseBody);
        }
    }
}